package com.nulldev.util.VariableAPI.util.strings.splitters;

import java.util.StringTokenizer;
import java.util.regex.Pattern;

import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.VariableAPI.util.strings.splitters.third_party.Splitter;
import com.nulldev.util.manage.MarkedForRemoval;

public class Splitters {

	private static final String[] BLANK_ARR = new String[0];

	public static String[] splitString(final String str, final String by) {
		return splitString(str, by, false);
	}

	public static String[] splitString(final String str, final String by, final boolean includeDelimIfOnEnd) {
		if (str == null || str.isEmpty()) {
			return BLANK_ARR;
		} else if (by == null || by.isEmpty()) {
			return StringsUtil.charArrToString(str);
		} else {
			final boolean hasDelimOnEnd = str.endsWith(by) && includeDelimIfOnEnd;
			final StringTokenizer tokenizer = new StringTokenizer(str, by);
			final int tokens = tokenizer.countTokens();
			final String[] words = new String[(hasDelimOnEnd ? (tokens + 1) : tokens)];
			for (int i = 0; i < (hasDelimOnEnd ? (words.length - 1) : (words.length)); i++) {
				words[i] = tokenizer.nextToken();
			}
			if (hasDelimOnEnd) {
				words[words.length - 1] = by;
			}
			return words;
		}
	}

	public static String[] splitStringWithDelims(final String str, final String by) {
		if (str == null || str.isEmpty()) {
			return BLANK_ARR;
		} else if (by == null || by.isEmpty()) {
			return StringsUtil.charArrToString(str);
		} else {
			final StringTokenizer tokenizer = new StringTokenizer(str, by, true);
			final String[] words = new String[tokenizer.countTokens()];
			int i = 0;
			while (tokenizer.hasMoreTokens()) {
				words[i] = tokenizer.nextToken();
				i++;
			}
			return words;
		}
	}

	public static Splitter byPattern(final String by) {
		return Splitter.onPattern(by);
	}

	@Deprecated
	@MarkedForRemoval(reason = "This is merely for compatibility purposes.")
	public static Splitter byPattern(final String str, final String by) {
		return Splitter.onPattern(by);
	}

	public static Splitter byPattern(final Pattern by) {
		return Splitter.onPattern(by.pattern());
	}

	@Deprecated
	@MarkedForRemoval(reason = "This is merely for compatibility purposes.")
	public static Splitter byPattern(final String str, final Pattern by) {
		return Splitter.onPattern(by.pattern());
	}
}
